import axios, { AxiosRequestConfig } from 'axios'
import Toast from 'vant/lib/toast'
import { getToken, removeToken } from './auth'

axios.defaults.baseURL ='/api'

const loginHost = 'https://samr-ty-dev.caeit.cyou'
const apiHost = 'https://samr-xtgz-dev.caeit.cyou'

const request = axios.create()

// 请求拦截器
request.interceptors.request.use(config => {
  // const Config = getToken('config') as Config
  // const DefaultToken = 'Basic dHJ1Y2stY2xpZW50OnRydWNrLXNlY3JldA=='
  if(config.url === '/api/oauth2/doLogin'){
    config.baseURL = loginHost
  }else{
    config.baseURL = apiHost
  }
  // config.baseURL = 'https://samr-xtgz-dev.caeit.cyou'
  
  const Token = getToken()
  if(Token){
    if (!config.headers) config.headers = {}
    config.headers.Authorization = 'Bearer ' + Token 
  }
  return config
}, err => {
  return Promise.reject(err)
})

// 响应拦截器
request.interceptors.response.use(res => {
  if (res.data.code !== 0 && res.data.code !== 200) {
    if(res.data.msg){
      if(res.data.msg == '无效token,请重新登陆'){
        removeToken()
      }
      Toast({
        message: res.data.msg,
        position: 'bottom',
      });
    }else{
      Toast({
        message: '数据错误',
        position: 'bottom',
      });
    }
    return Promise.reject(res)
  }
  return Promise.resolve(res)
}, err => {
  return Promise.reject(err)
})

export default <T = any>(config: AxiosRequestConfig) => {
  return request(config).then(res => {
    return res.data as T
  })
}
